<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\exception\ModelException;
use app\model\Attachment;
use app\model\Category;
use app\model\Route;
use app\model\Website;
use app\service\CategoryService;
use app\validate\CategoryValidate;
use think\exception\ValidateException;
use think\facade\Db;

class CategoryController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function index(Category $category): \think\response\Json
    {
        $websiteId = (int)input('param.website_id'); 
        if(!$websiteId){
            return jsonReturn(-1,'网站ID不能为空');
        }
        $lang = input('lang');
        $where = [
            'seller_id' => $this->admin['seller_id'],
            'website_id' => $websiteId,
        ];
        if(empty($lang)){
            $lang = 'zh';
        }
        $Website = new Website();
        $website = $Website -> getWebsite (['id'=>$websiteId,'seller_id'=>$this->admin['seller_id']])['data'];
        $domain = $website['domain'];
        if($lang != 'zh'){
            $domain = $domain .'/'.$lang;
        }
        $where['lang'] = $lang;
        $with = [
            'thumbnail' => function($query){
                $query->field('id,name,url');
            },'banner' => function($query){
                $query->field('id,name,url');
            }
        ];

        $categoryList = $category->with($with)->where($where)->select()->each(function (&$item)use($domain){
            if($item['type'] == 1 || $item['type'] == 4){
                if(!empty($item['alias'])){
                    if($item['alias'] == '/'){
                        $item['fullUrl'] = 'http://' . $domain;
                    }else{
                        $item['fullUrl'] = 'http://' . $domain . $item['alias'].'.'.config('route.url_html_suffix');
                    }
                }else{
                    $item['fullUrl'] = 'http://' . $domain . '/list/index/'.$item['id'].'.'.config('route.url_html_suffix');
                }
            }else if($item['type'] == 3){
                $item['fullUrl'] = $item['alias'];
            }else{
                $item['fullUrl'] = 'javascript:;';
            }
        });
        $categoryList = $categoryList->toArray();
        $categoryList = makeTree($categoryList);
        return jsonReturn(0,'success',$categoryList);
    }

    /**
     * 保存新建的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function save(CategoryService $categoryService,Category $Category): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            // 数据验证
            try{
                validate(CategoryValidate::class)->scene('save')->check($param);
            }catch(ValidateException $e){
                return jsonReturn(-1, $e->getError());
            }
            $param['seller_id'] = $this->admin['seller_id'];
            $category = $Category->existCategory(['title'=>$param['title'],'seller_id'=>$param['seller_id'],'website_id'=>$param['website_id'],'lang'=>$param['lang'],'parent_id'=>$param['parent_id']])['data'];
            if(!empty($category)){
                return jsonReturn(-2,'栏目已经存在');
            }
            if(!empty($param['alias']) && $param['alias'] != 'javascript:;'){
                $category = $Category->existCategory(['title'=>$param['alias'],'seller_id'=>$param['seller_id'],'website_id'=>$param['website_id'],'lang'=>$param['lang']])['data'];
            }
            if(!empty($category)){
                return jsonReturn(-3,'栏目别名已经存在');
            }
            return $categoryService -> createCategory($param);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 显示指定的资源
     *
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function read(Category $category,Attachment $attachment): \think\response\Json
    {
        $param = input('param.');
        try {
            validate(CategoryValidate::class)->scene('read')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }
        $param['seller_id']= $this->admin['seller_id'];
        $with = [
            'thumbnail' => function($query){
                $query->field('id,name,url');
            },'banner' => function($query){
                $query->field('id,name,url');
            }
        ];
        $res = $category->getCategory($param,$with);

        return json($res);
    }

    /**
     * 保存更新的资源
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function update(CategoryService $categoryService,Category $Category): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(CategoryValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $param['seller_id'] = $this->admin['seller_id'];
            $category = $Category->existCategory(['title'=>$param['title'],'seller_id'=>$param['seller_id'],'website_id'=>$param['website_id'],'lang'=>$param['lang'],'parent_id'=>$param['parent_id']])['data'];
            if(!empty($category) && $category['id'] != $param['id']){
                return jsonReturn(-2,'栏目已经存在');
            }
            $category = $Category->existCategory(['title'=>$param['alias'],'seller_id'=>$param['seller_id'],'website_id'=>$param['website_id']])['data'];
            if(!empty($category) && $category['id'] != $param['id']){
                return jsonReturn(-3,'栏目别名已经存在');
            }

            return $categoryService -> updateCategory($param);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 删除栏目
     * @param Category $category
     * @param Route $route
     * @return \think\response\Json
     */
    public function delete(Category $category,Route $route): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(CategoryValidate::class)->scene('delete')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
                'website_id' => $param['website_id'],
                'lang' => $param['lang']
            ];
            Db::startTrans();
            try {
                $res = $category->delCategory($where);
                $route->delRoute(['seller_id' => $this->admin['seller_id'],'category_id'=>$param['id']]);
                $route->getRoutes($param['website_id'], $this->admin['seller_id'], $param['lang']);
                $optAdmin = request()->admin;
                event("AdminOptLog",[
                    'admin_id' => $optAdmin['uid'],
                    'admin_name' => $optAdmin['name'],
                    'title'=>"栏目管理",
                    "content"=>"删除栏目,栏目ID为".$param['id'],
                ]);
                Db::commit();
            }catch (ModelException $me){
                Db::rollback();
                return jsonReturn(50023,$me->getMessage());
            }catch (\Exception $e){
                Db::rollback();
                return jsonReturn(50024,$e->getMessage());
            }
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * @throws ModelException
     */
    public function getModuleCate(Category $Category): \think\response\Json
    {
        $param = input('get.');
        try {
            validate(CategoryValidate::class)->scene('getModuleCate')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }
        $category = $Category->getCategoryList([
            ['seller_id','=',$this->admin['seller_id']],
            ['module_id','=',$param['model_id']],
            ['lang','=',$param['lang']],
            ['website_id','in',$param['site_id']],
        ],[],'id,title')['data']->toArray();
        $categoryList = makeTree($category);
        return jsonReturn(0,'success',$categoryList);
    }
}
